package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.service.AddressService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
public class AddressController {
    @Autowired
    private AddressService addressService;

    //查询我的地址列表
    @GetMapping("/address/list")
    public ResultInfo findList() {
        List<Address> addressList = addressService.findList();
        return ResultInfo.success(addressList);
    }

    //保存地址
    @PostMapping("/address")
    public ResultInfo save(@RequestBody Address address) {
        addressService.save(address);
        return ResultInfo.success(null);
    }

    //设置当前用户为默认地址
    @PutMapping("/address/default")
    public ResultInfo setDefault(@RequestBody Map<String, Long> map) {
        //获取参数
        Long id = map.get("id");
        //调用方法
        addressService.setDefault(id);
        return ResultInfo.success(null);

    }

    //查询默认地址
    @GetMapping("/address/default")
    public ResultInfo findDefault() {
        Address address = addressService.findDefault();
        if (address != null) {
            return ResultInfo.success(address);
        }else {
            return ResultInfo.error("没有默认地址");
        }
    }

    //地址回显
    @GetMapping("/address/{id}")
    public ResultInfo findById(@PathVariable("id") Long id){
        Address orderAddress = addressService.findById(id);
        return ResultInfo.success(orderAddress);
    }

    //地址更新
    @PutMapping("/address")
    public ResultInfo updateAddress(@RequestBody Address address) {
        addressService.updateAddress(address);
        return ResultInfo.success(null);
    }

    //删除地址
    @DeleteMapping("/address")
    public ResultInfo deleteAddress(Long[] ids) {
        System.out.println(Arrays.toString(ids));
        if (ids != null && ids.length > 0) {
            addressService.deleteAddress(ids);
        }
        return ResultInfo.success(null);
    }
}
